package entity.units;

import java.awt.Graphics2D;
import java.util.LinkedList;

import levels.PathFinder;
import loading.ImageLoader;
import math.Vector2D;

public abstract class GroundUnit extends Unit
{
	private int onPathLoc;
	private LinkedList<Vector2D> path;

	private PathFinder pf;
	
	public GroundUnit( Vector2D pos, ImageLoader img, PathFinder pf, double timeToTrain, int totalHealth )
	{
		super( pos, img, timeToTrain, totalHealth );
		
		path = null;
		
		this.pf = pf;
	}
	
	public void goTo( Vector2D end )
	{
		LinkedList<Vector2D> v = pf.findPath( this.getPosition(), end );
		
		if( v != null )
		{
			path = v;
			setState( MOVING );
		
			onPathLoc = 0;
		}
	}
	
	public void stop()
	{
		path = null;
		setState( STANDING );
		
		this.setSpeed( 0 );
	}
	
	public void update( double duration )
	{
		super.update( duration );
		
		if( getState() == MOVING )
		{
			if( getPosition().distance( path.get( onPathLoc ) ) < 15 )
				onPathLoc++;
			
			if( onPathLoc < path.size() )
				seek( path.get( onPathLoc ) );
			else
				stop();
		}
	}
	
	/**
	 * Probably not going to be used
	 * 
	 * @param decel decelerate either 1 (fast), 2 (medium), or 3 (slow) depending on situation
	 */
	public void arrive( int decel )
	{
		Vector2D toTarget = Vector2D.subtract( path.get( onPathLoc ), this.getPosition() );
		
		double dist = toTarget.getMagnitude();
		
		if( dist > 0 )
		{
			final double decelTweaker = 0.3;
			
			double speed = dist / ((double)decel * decelTweaker );
			
			speed = Math.min( speed, getMaxSpeed() );
			
			Vector2D desired = toTarget.multiply( speed / dist * 40 );
			
			this.setSteeringForce( Vector2D.subtract( desired, this.getVelocity() ) );
		}
	}
}
